<?php

namespace App\Models\CacheModel\chat\call;

use App\Models\Api\BaseCache;
use Exception;
use AstroTool\Cache\CacheManage;

class HzCallChatLastSendTimeRecord extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.hz_call_chat_last_send_time_record';

    protected $cacheModel = 'chat.user_call_chat_info';

    /**
     * 写入数据
     * @param $uid
     * @param $data
     * @return int
     * @throws Exception
     */
    public function SaveData($uid, $data)
    {
        try
        {
            $id = $this->allowField(true)->insertGetId($data);
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return 0;
        }
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->rmCache();
        return (int)$id;
    }

    /**
     *  更新 会话 最后发送时间 信息
     * @param int $uid
     * @param array $updateData
     * @throws Exception
     */
    public function UpdateData(int $uid, $updateData = [])
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->getDataAndSet(function () use ($uid)
        {
            return $this->getChatInfoStatusFromDms($uid);
        });
        //若用户数据则生成
        if (!$data)
        {
            $data = [
                'uid' => $uid,
                'rid' => 0,
                'status' => 1,
                'chat_id' => 0,
                'last_send_time' => 0,
            ];

            foreach ($updateData as $k => $v)
            {
                if (isset($data[$k]))
                {
                    $data[$k] = $v;
                }
            }

            $this->SaveData($uid, $data);
        } else
        {
            try
            {
                $this->where(['id' => $data['id']])->update($updateData);
                CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->setCache($data);
            }
            catch (\Exception $e)
            {
                \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            }
        }
    }

    /**
     * @param int $uid
     * @return array
     */
    public function getChatInfoStatusFromDms(int $uid): array
    {
        try
        {
            $data = $this->field('id,uid,status,rid,chat_id,last_send_time')->where(['uid' => $uid])->findOrFail()->toArray();
        }
        catch (Exception $e)
        {
            $data = [];
        }
        return $data;
    }
}
